/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtils {

    /**
     * @param classPathFilePath file path in class path
     * @return
     * @throws IOException
     */
    public static String readToString(String classPathFilePath) throws IOException {
        try (InputStream input = readToStream(classPathFilePath); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
            return output.toString();
        }
    }

    /**
     * @param classPathFilePath file path in class path
     * @return
     * @throws IOException
     */
    public static InputStream readToStream(String classPathFilePath) {
        return FileUtils.class.getResourceAsStream(classPathFilePath);
    }

    public static File getProcessLogFile(Path basePath, String preName) {
        long currentTime = System.currentTimeMillis();
        File newLogFile =
            new File(basePath.toFile(), String.format("%s.%s.%s", preName, "log", currentTime));
        try {
            boolean created = newLogFile.createNewFile();
            if (created) {
                log.info("create new file successfully and set last modified {}",
                    newLogFile.setLastModified(currentTime));
            }
        } catch (IOException e) {
            String fileName = String.format("%s.%s.%s", preName, "log", currentTime);
            log.error("Can not create new log file with name: {}", fileName, e);
            return null;
        }
        return newLogFile;
    }

}
